/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClasificacionDePizzasSmoothBox.java
 *
 * Created on 09-ene-2010, 20:54:42
 */
package clasificaciondepizzas;

import clasificaciondepizzas.models.SauceAndToppingModel;
import clasificaciondepizzas.operations.ImageOperations;
import com.sun.media.jai.widget.DisplayJAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Manuel
 */
public class ClasificacionDePizzasSmoothBox extends javax.swing.JDialog {

    /** Creates new form ClasificacionDePizzasSmoothBox */
    public ClasificacionDePizzasSmoothBox(java.awt.Frame parent) {
        super(parent);
        initComponents();
    }

    private void showAndOperationBox() {
        JFrame mainFrame = ClasificacionDePizzasApp.getApplication().getMainFrame();
        andOperationBox = new ClasificacionDePizzasAndOperationBox(mainFrame);
        andOperationBox.setLocationRelativeTo(this);
        image = ImageOperations.smooth(image, smoothSlider.getValue());
        andOperationBox.setSauceAndToppingModel(stm);
        andOperationBox.setImage(image);

        ClasificacionDePizzasApp.getApplication().show(andOperationBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        smoothedImageScrollPane = new javax.swing.JScrollPane();
        acceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        smoothSlider = new javax.swing.JSlider();
        sizeTextField = new javax.swing.JTextField();
        sizeLabel = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(clasificaciondepizzas.ClasificacionDePizzasApp.class).getContext().getResourceMap(ClasificacionDePizzasSmoothBox.class);
        setTitle(resourceMap.getString("smoothBox.title")); // NOI18N
        setModal(true);
        setName("smoothBox"); // NOI18N
        setResizable(false);

        smoothedImageScrollPane.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("smoothedImageScrollPane.viewportBorder.title"))); // NOI18N
        smoothedImageScrollPane.setName("smoothedImageScrollPane"); // NOI18N

        acceptButton.setText(resourceMap.getString("acceptButton.text")); // NOI18N
        acceptButton.setName("acceptButton"); // NOI18N
        acceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptButtonActionPerformed(evt);
            }
        });

        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        smoothSlider.setMajorTickSpacing(10);
        smoothSlider.setMaximum(10);
        smoothSlider.setMinimum(3);
        smoothSlider.setMinorTickSpacing(1);
        smoothSlider.setPaintLabels(true);
        smoothSlider.setSnapToTicks(true);
        smoothSlider.setValue(3);
        smoothSlider.setName("smoothSlider"); // NOI18N
        smoothSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                smoothSliderStateChanged(evt);
            }
        });

        sizeTextField.setText(((Integer)smoothSlider.getValue()).toString());
        sizeTextField.setName("sizeTextField"); // NOI18N
        sizeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeTextFieldActionPerformed(evt);
            }
        });

        sizeLabel.setText(resourceMap.getString("sizeLabel.text")); // NOI18N
        sizeLabel.setName("sizeLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(smoothedImageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sizeLabel)
                            .addComponent(acceptButton, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                            .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(sizeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)))
                    .addComponent(smoothSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(smoothedImageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(acceptButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(sizeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(smoothSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void smoothSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_smoothSliderStateChanged
        PlanarImage previewImage;

        sizeTextField.setText(((Integer) smoothSlider.getValue()).toString());

        try {
            // previsualización en miniatura del suavizado
            previewImage = ImageOperations.smooth(thumbnail, smoothSlider.getValue());
            previewImage = ImageOperations.binarize(previewImage, 128.);
            DisplayJAI display = new DisplayJAI(previewImage);
            smoothedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el suavizado.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_smoothSliderStateChanged

    private void sizeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeTextFieldActionPerformed
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado
        int value = Integer.parseInt(sizeTextField.getText()); // valor del campo de texto

        // el control de desplazamiento se actualiza junto con el campo de texto
        smoothSlider.setValue(value);

        try {
            // previsualización en miniatura del suavizado
            previewImage = ImageOperations.smooth(thumbnail, smoothSlider.getValue());
            previewImage = ImageOperations.binarize(previewImage, 128.);
            DisplayJAI display = new DisplayJAI(previewImage);
            smoothedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el suavizado.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_sizeTextFieldActionPerformed

    private void acceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptButtonActionPerformed
        setVisible(false);
        showAndOperationBox();
        dispose();
    }//GEN-LAST:event_acceptButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel sizeLabel;
    private javax.swing.JTextField sizeTextField;
    private javax.swing.JSlider smoothSlider;
    private javax.swing.JScrollPane smoothedImageScrollPane;
    // End of variables declaration//GEN-END:variables
    private PlanarImage image;
    private PlanarImage thumbnail;
    private ClasificacionDePizzasAndOperationBox andOperationBox;
    private SauceAndToppingModel stm;

    void setImage(PlanarImage image) {
        this.image = image;
        thumbnail = this.image;
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado

        // si la imagen supera el tamaño del panel con desplazamiento se escala a un tamaño menor
        if (image.getWidth() > smoothedImageScrollPane.getWidth() || image.getHeight() > smoothedImageScrollPane.getHeight()) {
            // si la imagen supera la anchura del panel con desplazamiento se escala a una anchura menor
            if (image.getWidth() > image.getHeight()) {
                float ratio = (float) smoothedImageScrollPane.getWidth() / (float) image.getWidth();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            } // si la imagen supera la altura del panel con desplazamiento se escala a una altura menor
            else {
                float ratio = (float) smoothedImageScrollPane.getHeight() / (float) image.getHeight();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            }
        }

        try {
            // previsualización en miniatura del suavizado
            previewImage = ImageOperations.smooth(thumbnail, smoothSlider.getValue());
            previewImage = ImageOperations.binarize(previewImage, 128.);
            DisplayJAI display = new DisplayJAI(previewImage);
            smoothedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el suavizado.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    void setSauceAndToppingModel(SauceAndToppingModel stm) {
        this.stm = stm;
    }
}
